//
//  NWGoodSubjectTitleCell.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/3.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NWGoodSubjectTitleCell.h"
@interface NWGoodSubjectTitleCell ()<DTAttributedTextContentViewDelegate, DTLazyImageViewDelegate>
@property(nonatomic, strong) DTAttributedLabel *titleAttrLabel;
@property(nonatomic, strong) QMUIButton *seeAnalysisBtn;
@property(nonatomic, strong) QMUIButton *continueAnswerQuestionBtn;
@property(nonatomic, strong, readwrite) UIView *centerContentView;
@end
@implementation NWGoodSubjectTitleCell

- (BOOL)shouldUpdateCellWithObject:(id)object atIndexPath:(NSIndexPath *)indexPath
{
        self.subjectModel.indexPath = indexPath;
        self.subjectModel = object;
        return YES;
}
- (void)setSubjectModel:(NWGoodSubjectModel *)subjectModel
{
        _subjectModel = subjectModel;
        [self updateContent];
}
- (void)updateContent
{
        self.titleAttrLabel.attributedString = [self attributedStringForHtmlString:self.subjectModel.question_title];
}
- (void)setupView
{
        [super setupView];
        
        UIView *contentView = [[UIView alloc] init];
        [self.contentView addSubview:contentView];
        
        [contentView addSubview:self.titleAttrLabel];
        [contentView addSubview:self.centerContentView];
        
        
        UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:@[self.seeAnalysisBtn,self.continueAnswerQuestionBtn]];
        stackView.axis = UILayoutConstraintAxisHorizontal;
        stackView.distribution = UIStackViewDistributionFillEqually;
        stackView.alignment = UIStackViewAlignmentCenter;
        stackView.spacing = __WGWidth(1);
        [contentView addSubview:stackView];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = UIColorHex(0xE1E1E1);
        [stackView addSubview:lineView];
        
        [contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.contentView).valueOffset([NSValue valueWithUIEdgeInsets:UIEdgeInsetsMake(__WGHeight(15), __WGWidth(16), __WGHeight(15), __WGWidth(16))]);
        }];
        
        [self.titleAttrLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.equalTo(contentView);
        }];
        
        [self.centerContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.titleAttrLabel.mas_bottom);
                make.left.right.equalTo(contentView);
        }];
        
        [stackView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.centerContentView.mas_bottom);
                make.left.right.bottom.equalTo(contentView);
        }];
        
        [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(stackView);
                make.height.mas_equalTo(__WGHeight(20));
                make.width.mas_equalTo(__WGWidth(1));
        }];
}
- (void)linkPushed:(DTLinkButton *)button
{
        NSURL *URL = button.URL;
        
        if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]])
        {
                [[UIApplication sharedApplication] openURL:[URL absoluteURL]];
        }
}


- (NSAttributedString *)attributedStringForHtmlString:(NSString *)htmlString
{
        // Load HTML data
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        
        // Create attributed string from HTML
        CGSize maxImageSize = CGSizeMake(self.centerContentView.width, __WGHeight(80));
        
        // example for setting a willFlushCallback, that gets called before elements are written to the generated attributed string
        void (^callBackBlock)(DTHTMLElement *element) = ^(DTHTMLElement *element) {
                
                // the block is being called for an entire paragraph, so we check the individual elements
                
                for (DTHTMLElement *oneChildElement in element.childNodes)
                {
                        // if an element is larger than twice the font size put it in it's own block
                        if (oneChildElement.displayStyle == DTHTMLElementDisplayStyleInline && oneChildElement.textAttachment.displaySize.height > 2.0 * oneChildElement.fontDescriptor.pointSize)
                        {
                                oneChildElement.displayStyle = DTHTMLElementDisplayStyleBlock;
                                oneChildElement.paragraphStyle.minimumLineHeight = element.textAttachment.displaySize.height;
                                oneChildElement.paragraphStyle.maximumLineHeight = element.textAttachment.displaySize.height;
                        }
                }
        };
        UIFont *font = WGSystem13Font;
        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                                       NSTextSizeMultiplierDocumentOption : @(1),
                                                                                       DTMaxImageSize : [NSValue valueWithCGSize:maxImageSize],
                                                                                       DTDefaultFontFamily : font.familyName,
                                                                                       DTDefaultFontName : font.fontName,
                                                                                       DTDefaultFontSize : @(13),
                                                                                       DTDefaultLinkColor : UIColorHex(0x333333),
                                                                                       DTDefaultTextColor : UIColorHex(0x333333),
                                                                                       DTWillFlushBlockCallBack : callBackBlock,
                                                                                       }];
        NSAttributedString *string = [[NSAttributedString alloc] initWithHTMLData:data options:options documentAttributes:NULL];
        
        return string;
}

/// MARK: - DTCoreText delegate
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
        if ([attachment isKindOfClass:[DTImageTextAttachment class]])
        {
                // if the attachment has a hyperlinkURL then this is currently ignored
                DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
                imageView.delegate = self;
                imageView.contentView = attributedTextContentView;
                
                // sets the image if there is one
                imageView.image = [(DTImageTextAttachment *)attachment image];
                
                // url for deferred loading
                imageView.url = attachment.contentURL;
                
                // if there is a hyperlink then add a link button on top of this image
                if (attachment.hyperLinkURL)
                {
                        // NOTE: this is a hack, you probably want to use your own image view and touch handling
                        // also, this treats an image with a hyperlink by itself because we don't have the GUID of the link parts
                        imageView.userInteractionEnabled = YES;
                        
                        DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:imageView.bounds];
                        button.URL = attachment.hyperLinkURL;
                        button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
                        button.GUID = attachment.hyperLinkGUID;
                        
                        // use normal push action for opening URL
                        [button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
                        
                        [imageView addSubview:button];
                }
                
                return imageView;
        }
        return nil;
}

/// MARK:  - DTLazyImageViewDelegate
- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size
{
        NSURL *url = lazyImageView.url;
        CGSize imageSize = size;
        
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
        
        BOOL didUpdate = NO;
        
        // update all attachments that match this URL (possibly multiple images with same size)
        for (DTTextAttachment *oneAttachment in [lazyImageView.contentView.layoutFrame textAttachmentsWithPredicate:pred])
        {
                // update attachments that have no original size, that also sets the display size
                if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero))
                {
                        oneAttachment.originalSize = imageSize;
                        
                        didUpdate = YES;
                }
        }
        
        if (didUpdate)
        {
                // layout might have changed due to image sizes
                // do it on next run loop because a layout pass might be going on
                dispatch_async(dispatch_get_main_queue(), ^{
                        [lazyImageView.contentView relayoutText];
                });
        }
}

/// MARK: - Lazy
- (DTAttributedLabel *)titleAttrLabel
{
        if (_titleAttrLabel == nil) {
                _titleAttrLabel = [[DTAttributedLabel alloc] init];
                _titleAttrLabel.numberOfLines = 0;
                _titleAttrLabel.delegate = self;
                _titleAttrLabel.shouldDrawLinks = NO;
                _titleAttrLabel.shouldDrawImages = YES;
        }
        return _titleAttrLabel;
}
- (QMUIButton *)seeAnalysisBtn
{
        if (_seeAnalysisBtn == nil) {
                _seeAnalysisBtn = [[QMUIButton alloc] qmui_initWithImage:[UIImage cha_kan_jie_xi] title:@"查看解析"];
                _seeAnalysisBtn.titleLabel.font = WGSystem14Font;
                [_seeAnalysisBtn setTitleColor:UIColorBlack forState:(UIControlStateNormal)];
        }
        return _seeAnalysisBtn;
}
- (QMUIButton *)continueAnswerQuestionBtn
{
        if (_continueAnswerQuestionBtn == nil) {
                _continueAnswerQuestionBtn = [[QMUIButton alloc] qmui_initWithImage:[UIImage ji_xu_da_ti] title:@"继续答题"];
                _continueAnswerQuestionBtn.titleLabel.font = WGSystem14Font;
                [_continueAnswerQuestionBtn setTitleColor:UIColorBlack forState:(UIControlStateNormal)];
        }
        return _continueAnswerQuestionBtn;
}
- (UIView *)centerContentView
{
        if (_centerContentView == nil) {
                _centerContentView = [[UIView alloc] init];
                _centerContentView.backgroundColor = [UIColor clearColor];
        }
        return _centerContentView;
}
@end
